<template>
  <li>
    <span @click="toggle">
      <i :class="['icon', (isFolder || isDynamicFolder) ? folderIcon : 'file-text']"></i>
      <!--一级的菜单名-->
      {{ model.menuName }}
    </span>
    <ul v-if="isOpen">
      <!--二三级菜单-->
      <tree-menu v-for="item in model.children" :key="item.id" :model="item"></tree-menu>
    </ul>
  </li>
</template>

<script>
  export default {
    name: 'treeMenu',
    props: {
      model: Object,
      subMenuData: Object
    },
    data() {
      return {
        folderIcon: 'folder',
        isDynamicFolder: false,
        isOpen: false
      }
    },
    computed: {
      isFolder() {
        return !!(this.model.children && this.model.children.length)
      }
    },
    watch: {
      isDynamicFolder() {
        this.isOpen = true
        this.folderIcon = 'folder-open'
      }
    },
    methods: {
      toggle() {
        const menuData = this.model;
        const subMenuData = this.subMenuData;
        if (subMenuData && (menuData.id === subMenuData.parentId && subMenuData.list) && !menuData.children) {
          menuData.children = subMenuData.list;
          this.isDynamicFolder = !!(menuData.children && menuData.children.length);
          this.isOpen = true;
          this.folderIcon = 'folder-open'
        }
        if (this.isFolder || this.isDynamicFolder) {
          this.isOpen = !this.isOpen;
          this.folderIcon = this.isOpen ? 'folder' : 'folder-open'
        }
      }
    }
  }
</script>

<style>
  ul {
    list-style: none;
    padding-top: 30px;
  }

  i.icon {
    display: inline-block;
    width: 15px;
    height: 15px;
    background-repeat: no-repeat;
    vertical-align: middle;
  }

  .icon.folder {
    background: url("../../assets/folder.png");
  }

  .icon.folder-open {
    background: url("../../assets/folder-open.png");
  }

  .icon.file-text {
    background: url("../../assets/file-text.png");
  }

  .tree-menu li {
    line-height: 1.5;
  }

  .tree-menu li ul {
    margin-left: 10px;
    color: #007aff;
  }

  .tree-menu li ul li {
    background: #f2f2f2;
    border-top: 1px solid #d7d7d7;
  }

  .tree-menu li ul li ul {
    margin-left: 10px;
    color: red;
  }
</style>
